package com.fs.system.service.impl;

import java.util.concurrent.TimeUnit;

import com.fs.common.constant.CacheConstants;
import com.fs.common.constant.Constants;
import com.fs.common.core.pojo.SysUser;
import com.fs.common.exception.user.UserPasswordNotMatchException;
import com.fs.common.exception.user.UserPasswordRetryLimitExceedException;
import com.fs.common.util.RedisCache;
import com.fs.common.util.sign.PasswordUtils;
import com.fs.system.config.SysPasswordProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import sun.misc.MessageUtils;

/**
 * 登录密码方法
 */
@Service
public class SysPasswordService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysPasswordProperties passwordProperties;



    /**
     * 登录账户密码错误次数缓存键名
     * 
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username){
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUser user,String password) {
        String username  = user.getUserName();
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(passwordProperties.getMaxRetryCount()).intValue()) {
            throw new UserPasswordRetryLimitExceedException(passwordProperties.getMaxRetryCount(), passwordProperties.getLockTime());
        }

        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getCacheKey(username), retryCount, passwordProperties.getLockTime(), TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        }
        else{
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUser user, String rawPassword){
        return PasswordUtils.verify(rawPassword,user.getPassword());
    }

    public void clearLoginRecordCache(String loginName){
        if (redisCache.hasKey(getCacheKey(loginName))){
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}